package cn.littlehx.spring_boot_test2_2.service.impl;

import cn.littlehx.spring_boot_test2_2.domain.Student;
import cn.littlehx.spring_boot_test2_2.exception.REnum;
import cn.littlehx.spring_boot_test2_2.exception.RException;
import cn.littlehx.spring_boot_test2_2.repository.StudentRepository;
import cn.littlehx.spring_boot_test2_2.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Override
    public Page<Student> findAll(Example<Student> studentExample,Pageable pageable) {
        return studentRepository.findAll(studentExample, pageable);
    }

    @Override
    public Page<Student> findAll(Pageable pageable) {

        return studentRepository.findAll(pageable);
    }

    @Autowired
    private StudentRepository studentRepository;

    public List<Student> findALL() {
        return studentRepository.findAll();
    }

    /**
     * 按id进行查询
     *
     * @param id 主键,整数
     * @return
     */
    public Student findById(Integer id) {
        return studentRepository.findById(id).orElse(null);
    }

    /**
     * 按名字进行查询,like
     *
     * @param name 主键,整数
     * @return
     */
    public List<Student> findByNameLike(String name) {
        return studentRepository.findByNameLike("%" + name + "%");
    }

    /**
     * 按名字和密码进行查询
     *
     * @param name
     * @param password
     * @return
     */
    public List<Student> findByNameAndPassword(String name, String password) throws Exception {
        List<Student> byNameAndPassword = studentRepository.findByNameAndPassword(name, password);
        if(byNameAndPassword.size()>0){
            return byNameAndPassword;
        }else{
            throw new RException(REnum.LOGIN_ERROR);
        }



    }

    /**
     * 插入学生
     *
     * @param student
     */
    public Student insert(Student student) {
        Student save = studentRepository.save(student);
        return save;
    }

    /**
     * 更新学生
     *
     * @param student
     */
    public Student update(Student student) {
        return studentRepository.save(student);
    }

    /**
     * 删除学生
     *
     * @param id
     */
    public void delete(Integer id) {
//        studentRepository.delete(student);
        studentRepository.deleteById(id);
    }
}
